<!DOCTYPE html>

<html lang="
zh-CN"
    >

        <head>
            
                <title>
                    
                        JAVA-网络编程 -
                            
                                shanX&#39;s Blog
                </title>
                <meta charset="UTF-8">
                <meta name="description" content="">
                <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=5">
                
                    

                        <link rel="shortcut icon" href="/image/author.png" type="image/png" />
                        <meta name="description" content="网络编程">
<meta property="og:type" content="article">
<meta property="og:title" content="JAVA-网络编程">
<meta property="og:url" content="https://rhymexmove.github.io/2021/04/12/6b4cf36b2046/index.html">
<meta property="og:site_name" content="shanX&#39;s Blog">
<meta property="og:description" content="网络编程">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-04-12T14:50:21.000Z">
<meta property="article:modified_time" content="2022-04-07T17:25:27.697Z">
<meta property="article:author" content="shanX">
<meta property="article:tag" content="java基础">
<meta property="article:tag" content="狂神说">
<meta name="twitter:card" content="summary">
                            <link rel="stylesheet" href="https://cdn.jsdelivr.net/combine/npm/highlight.js@9.15.8/styles/atom-one-dark.css,gh/theme-nexmoe/hexo-theme-nexmoe@latest/source/lib/mdui_043tiny/css/mdui.css,gh/theme-nexmoe/hexo-theme-nexmoe@latest/source/lib/iconfont/iconfont.css,gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css?v=233"
                                crossorigin>
                            <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/justifiedGallery@3.8.1/dist/css/justifiedGallery.min.css">
                            <!--适用于 Retina 屏的 iPad-->
                            <link rel="apple-touch-icon-precomposed" sizes="144x144" href="https://cdn.jsdelivr.net/gh/RhymeXmove/blogimg@latest/author.png">
                            <!--适用于 Retina 屏的 iPhone-->
                            <link rel="apple-touch-icon-precomposed" sizes="120x120" href="https://cdn.jsdelivr.net/gh/RhymeXmove/blogimg@latest/author.png">
                            <!--适用于非 Retina 屏的 iPad-->
                            <link rel="apple-touch-icon-precomposed" sizes="72x72" href="https://cdn.jsdelivr.net/gh/RhymeXmove/blogimg@latest/author.png">
                            <!--适用于非 Retina 屏的 iPhone-->
                            <link rel="apple-touch-icon-precomposed" href="https://cdn.jsdelivr.net/gh/RhymeXmove/blogimg@latest/author.png">
                            
                                <link rel="stylesheet" href="//at.alicdn.com/t/font_2490857_fmjyoao96km.css">
                                
                                    <link rel="stylesheet" href="/css/style.css?v=1649858550947">
        <meta name="generator" content="Hexo 5.4.0"></head>

        <body class="mdui-drawer-body-left">
            
                <div id="nexmoe-background">
                    <div class="nexmoe-bg" style="background-image: url(https://cdn.jsdelivr.net/gh/RhymeXmove/blogimg@latest/cover/5887c2f1-b191-4890-aab5-2ce62d9955df.jpg)"></div>
                    <div class="mdui-appbar mdui-shadow-0">
                        <div class="mdui-toolbar">
                            <a mdui-drawer="{target: '#drawer', swipe: true}" title="menu" class="mdui-btn mdui-btn-icon mdui-ripple"><i class="mdui-icon nexmoefont icon-menu"></i></a>
                            <div class="mdui-toolbar-spacer"></div>
                            <!--<a href="javascript:;" class="mdui-btn mdui-btn-icon"><i class="mdui-icon material-icons">search</i></a>-->
                            <a href="/" title="shanX" class="mdui-btn mdui-btn-icon"><img src="https://cdn.jsdelivr.net/gh/RhymeXmove/blogimg@latest/author.png" alt="shanX"></a>
                        </div>
                    </div>
                </div>
                <div id="nexmoe-header">
                    <div class="nexmoe-drawer mdui-drawer" id="drawer">
    <div class="nexmoe-avatar mdui-ripple">
        <a href="/" title="shanX">
            <img src="https://cdn.jsdelivr.net/gh/RhymeXmove/blogimg@latest/author.png" alt="shanX" alt="shanX">
        </a>
    </div>
    <div class="nexmoe-count nexmoe-widget-wrap">
        <div><span>文章</span>30</div>
        <div><span>标签</span>16</div>
        <div><span>分类</span>8</div>
    </div>
    <div class="nexmoe-list mdui-list nexmoe-widget-wrap" mdui-collapse="{accordion: true}">
        
        <a class="nexmoe-list-item mdui-list-item mdui-ripple" href="/" title="回到首页">
            <i class="mdui-list-item-icon nexmoefont icon-home"></i>
            <div class="mdui-list-item-content">
                回到首页
            </div>
        </a>
        
        <a class="nexmoe-list-item mdui-list-item mdui-ripple" href="/archives.html" title="文章归档">
            <i class="mdui-list-item-icon nexmoefont icon-container"></i>
            <div class="mdui-list-item-content">
                文章归档
            </div>
        </a>
        
        <a class="nexmoe-list-item mdui-list-item mdui-ripple" href="/cesium-test/index.html" title="Cesium">
            <i class="mdui-list-item-icon nexmoefont icon-Cesium-copy"></i>
            <div class="mdui-list-item-content">
                Cesium
            </div>
        </a>
        
        <a class="nexmoe-list-item mdui-list-item mdui-ripple" href="/cesium-covid/index.html" title="全球疫情">
            <i class="mdui-list-item-icon nexmoefont icon-areachart"></i>
            <div class="mdui-list-item-content">
                全球疫情
            </div>
        </a>
        
        <a class="nexmoe-list-item mdui-list-item mdui-ripple" href="/about.html" title="关于博客">
            <i class="mdui-list-item-icon nexmoefont icon-info-circle"></i>
            <div class="mdui-list-item-content">
                关于博客
            </div>
        </a>
        
    </div>
    <aside id="nexmoe-sidebar">
  
  <div class="nexmoe-widget-wrap">
    <div class="nexmoe-widget nexmoe-search">
        <form id="search_form" action_e="https://cn.bing.com/search?q=rhymexmove.github.io" onsubmit="return search();">
            <label><input id="search_value" name="q" type="search" placeholder="搜索"></label>
        </form>
    </div>
</div>
  
  <div class="nexmoe-widget-wrap">
    <div class="nexmoe-widget nexmoe-social">
        <a class="mdui-ripple" href="https://space.bilibili.com/20666214" target="_blank" mdui-tooltip="{content: '哔哩哔哩'}" style="color: rgb(231, 106, 141);background-color: rgba(231, 106, 141, .15);">
            <i class="nexmoefont icon-bilibili"></i>
        </a><a class="mdui-ripple" href="https://github.com/RhymeXmove/" target="_blank" mdui-tooltip="{content: 'GitHub'}" style="color: rgb(231, 106, 141);background-color: rgba(231, 106, 141, .15);">
            <i class="nexmoefont icon-github"></i>
        </a><a class="mdui-ripple" href="https://gitee.com/shanxin123/" target="_blank" mdui-tooltip="{content: 'Gitee'}" style="color: rgb(220,20,60);background-color: rgba(220,20,60, .15);">
            <i class="nexmoefont icon-gitee"></i>
        </a>
    </div>
</div>
  
  
    <div class="nexmoe-widget-wrap">
        <h3 class="nexmoe-widget-title">
            文章分类
        </h3>
        <div class="nexmoe-widget">

            <ul class="category-list">

                


                    

                        

                            <li class="category-list-item">
                                <a class="category-list-link" href="/categories/mysql/">
                                    -mysql
                                </a>
                                <span class="category-list-count">1</span>
                            </li>

                            

                            <li class="category-list-item">
                                <a class="category-list-link" href="/categories/Cesium/">
                                    Cesium
                                </a>
                                <span class="category-list-count">3</span>
                            </li>

                            

                            <li class="category-list-item">
                                <a class="category-list-link" href="/categories/DB/">
                                    DB
                                </a>
                                <span class="category-list-count">2</span>
                            </li>

                            

                            <li class="category-list-item">
                                <a class="category-list-link" href="/categories/Leetcode/">
                                    Leetcode
                                </a>
                                <span class="category-list-count">4</span>
                            </li>

                            

                            <li class="category-list-item">
                                <a class="category-list-link" href="/categories/Vue/">
                                    Vue
                                </a>
                                <span class="category-list-count">2</span>
                            </li>

                            

                            <li class="category-list-item">
                                <a class="category-list-link" href="/categories/blog搭建/">
                                    blog搭建
                                </a>
                                <span class="category-list-count">1</span>
                            </li>

                            

                            <li class="category-list-item">
                                <a class="category-list-link" href="/categories/java/">
                                    java
                                </a>
                                <span class="category-list-count">12</span>
                            </li>

                            

                            <li class="category-list-item">
                                <a class="category-list-link" href="/categories/资源/">
                                    资源
                                </a>
                                <span class="category-list-count">1</span>
                            </li>

                            
            </ul>

        </div>
    </div>
    
  
  
  <div class="nexmoe-widget-wrap">
    <div id="randomtagcloud" class="nexmoe-widget tagcloud nexmoe-rainbow">
      <a href="/tags/DB/" style="font-size: 10px;">-DB</a> <a href="/tags/Cesium/" style="font-size: 12.5px;">Cesium</a> <a href="/tags/GIS/" style="font-size: 10px;">GIS</a> <a href="/tags/Leetcode/" style="font-size: 15px;">Leetcode</a> <a href="/tags/Vue/" style="font-size: 12.5px;">Vue</a> <a href="/tags/blog%E6%90%AD%E5%BB%BA/" style="font-size: 10px;">blog搭建</a> <a href="/tags/echart/" style="font-size: 10px;">echart</a> <a href="/tags/java/" style="font-size: 10px;">java</a> <a href="/tags/java%E5%9F%BA%E7%A1%80/" style="font-size: 20px;">java基础</a> <a href="/tags/mysql/" style="font-size: 10px;">mysql</a> <a href="/tags/spring/" style="font-size: 10px;">spring</a> <a href="/tags/vue/" style="font-size: 10px;">vue</a> <a href="/tags/%E6%89%B9%E5%A4%84%E7%90%86%E5%B7%A5%E5%85%B7/" style="font-size: 10px;">批处理工具</a> <a href="/tags/%E6%95%B0%E6%8D%AE%E5%BA%93/" style="font-size: 10px;">数据库</a> <a href="/tags/%E7%8B%82%E7%A5%9E%E8%AF%B4/" style="font-size: 17.5px;">狂神说</a> <a href="/tags/%E8%B5%84%E6%BA%90/" style="font-size: 10px;">资源</a>
    </div>
    
  </div>

  
  
  <div class="nexmoe-widget-wrap">
    <h3 class="nexmoe-widget-title">文章归档</h3>
    <div class="nexmoe-widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2022/">2022</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/">2021</a><span class="archive-list-count">29</span></li></ul>
    </div>
  </div>



  
  
  <div class="nexmoe-widget-wrap">
    <h3 class="nexmoe-widget-title">最新文章</h3>
    <div class="nexmoe-widget">
      <ul>
        
          <li>
            <a href="/2022/04/13/7533e8f3cb4c/">mysql查询数据库内全部表名；查询表内全部字段名</a>
          </li>
        
          <li>
            <a href="/2021/09/26/ee931b51117c/">什么是计算机图形学？</a>
          </li>
        
          <li>
            <a href="/2021/09/08/9adeea845004/">中国城市坐标(包含市辖区)</a>
          </li>
        
          <li>
            <a href="/2021/08/31/7ba201dda6cb/">Cesium billboard贴地形表</a>
          </li>
        
          <li>
            <a href="/2021/08/09/0d3ed7d31d83/">Vue中使用Vue-jsonp请求jsonp数据</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
    <div class="nexmoe-copyright">
        &copy; 2022 shanX
        Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
        & <a href="https://github.com/theme-nexmoe/hexo-theme-nexmoe" target="_blank">Nexmoe</a>
        
    </div>
</div><!-- .nexmoe-drawer -->
                </div>
                <div id="nexmoe-content">
                    <div class="nexmoe-primary">
                        <div class="nexmoe-post">

  <div class="nexmoe-post-right">
    
      <div class="nexmoe-fixed">
        <div class="nexmoe-valign">
            <div class="nexmoe-toc">
                
                
                  <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B"><span class="toc-number">1.</span> <span class="toc-text">网络编程</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A6%82%E8%BF%B0"><span class="toc-number">1.1.</span> <span class="toc-text">概述</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B%E7%9A%84%E7%9B%AE%E7%9A%84%EF%BC%9A"><span class="toc-number">1.1.1.</span> <span class="toc-text">网络编程的目的：</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%83%B3%E8%A6%81%E8%BE%BE%E5%88%B0%E8%BF%99%E4%B8%AA%E6%95%88%E6%9E%9C%E9%9C%80%E8%A6%81%E4%BB%80%E4%B9%88"><span class="toc-number">1.1.2.</span> <span class="toc-text">想要达到这个效果需要什么</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BD%91%E7%BB%9C%E9%80%9A%E4%BF%A1%E7%9A%84%E8%A6%81%E7%B4%A0"><span class="toc-number">1.2.</span> <span class="toc-text">网络通信的要素</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#IP"><span class="toc-number">1.3.</span> <span class="toc-text">IP</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%AB%AF%E5%8F%A3"><span class="toc-number">1.4.</span> <span class="toc-text">端口</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE"><span class="toc-number">1.5.</span> <span class="toc-text">通信协议</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#TCP"><span class="toc-number">1.6.</span> <span class="toc-text">TCP</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#TCP%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0"><span class="toc-number">1.7.</span> <span class="toc-text">TCP文件上传</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Tomcat"><span class="toc-number">1.8.</span> <span class="toc-text">Tomcat</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#UDP"><span class="toc-number">1.9.</span> <span class="toc-text">UDP</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A1%88%E4%BE%8B%EF%BC%9AUDP%E5%AE%9E%E7%8E%B0%E8%81%8A%E5%A4%A9"><span class="toc-number">1.10.</span> <span class="toc-text">案例：UDP实现聊天</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#URL"><span class="toc-number">1.11.</span> <span class="toc-text">URL</span></a></li></ol></li></ol>
                
            </div>
        </div>
      </div>
    
  </div>

  <article>
    
        <div class="nexmoe-post-cover" style="padding-bottom: NaN%;"> 
            <img data-src="https://cdn.jsdelivr.net/gh/RhymeXmove/blogimg@latest/cover/JAVA.png" data-sizes="auto" alt="JAVA-网络编程" class="lazyload">
            <h1>JAVA-网络编程</h1>
        </div>
    
    
    <div class="nexmoe-post-meta nexmoe-rainbow-fill" style="margin:10px 0!important;">
    <a><i class="nexmoefont icon-calendar-fill"></i>2021年04月12日</a>
    <a><i class="nexmoefont icon-areachart"></i>2.5k 字</a>
    <a><i class="nexmoefont icon-time-circle-fill"></i>大概 13 分钟</a>
</div>

    <h1 id="网络编程"><a href="#网络编程" class="headerlink" title="网络编程"></a>网络编程</h1><span id="more"></span>

<h2 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h2><p>类似于平信信件</p>
<p>其中涉及计算机网络基本概念，网络编程的目的就是传播交流信息、数据交换、通信；达到的效果是需要如何准确定位到网络上的一台主机（IP、端口、资源），对主机进行数据传输</p>
<p>与JAVAWEB网页编程的B/S架构不同，网络编程是C/S编程。</p>
<p>计算机网络是指将<a target="_blank" rel="noopener" href="https://baike.baidu.com/item/%E5%9C%B0%E7%90%86">地理</a>位置不同的具有独立功能的多台<a target="_blank" rel="noopener" href="https://baike.baidu.com/item/%E8%AE%A1%E7%AE%97%E6%9C%BA/140338">计算机</a>及其外部设备，通过通信线路连接起来，在<a target="_blank" rel="noopener" href="https://baike.baidu.com/item/%E7%BD%91%E7%BB%9C%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/3997">网络操作系统</a>，<a target="_blank" rel="noopener" href="https://baike.baidu.com/item/%E7%BD%91%E7%BB%9C%E7%AE%A1%E7%90%86%E8%BD%AF%E4%BB%B6/6579078">网络管理软件</a>及<a target="_blank" rel="noopener" href="https://baike.baidu.com/item/%E7%BD%91%E7%BB%9C%E9%80%9A%E4%BF%A1%E5%8D%8F%E8%AE%AE/4438611">网络通信协议</a>的管理和协调下，实现<a target="_blank" rel="noopener" href="https://baike.baidu.com/item/%E8%B5%84%E6%BA%90%E5%85%B1%E4%BA%AB/233480">资源共享</a>和信息传递的计算机系统。</p>
<h3 id="网络编程的目的："><a href="#网络编程的目的：" class="headerlink" title="网络编程的目的："></a>网络编程的目的：</h3><p>交流信息，数据交换，通信。</p>
<h3 id="想要达到这个效果需要什么"><a href="#想要达到这个效果需要什么" class="headerlink" title="想要达到这个效果需要什么"></a>想要达到这个效果需要什么</h3><ol>
<li>如何准确地定位网络上的一台主机，192.168.0.176：3553   IP :  端口，定位到这个计算机上的某个资源。</li>
<li>找到了这个主机，如何传输数据？</li>
<li>javaweb : 网页编程  B/S             网络编程 ：TCP/IP 、C/S</li>
</ol>
<h2 id="网络通信的要素"><a href="#网络通信的要素" class="headerlink" title="网络通信的要素"></a>网络通信的要素</h2><p>如何实现网络的通信？</p>
<ol>
<li><strong>通信双方的ip</strong>、<strong>端口号</strong></li>
<li><strong>规则</strong>：TCP/IP 、OSI</li>
</ol>
<p>小结：</p>
<ol>
<li>网络编程中两个主要的问题<ul>
<li>如何准确定位到网络上一台或多台主机</li>
<li>找到主机之后如何进行通信</li>
</ul>
</li>
<li>网络编程中的要素<ul>
<li>IP和端口号</li>
<li>网络通信协议 UDP TCP/IP</li>
</ul>
</li>
<li>万物皆对象</li>
</ol>
<h2 id="IP"><a href="#IP" class="headerlink" title="IP"></a>IP</h2><p>ip地址：InetAddress</p>
<ul>
<li><p>唯一定位一台网络上的计算机</p>
</li>
<li><p>127.0.0.1 本机localhost</p>
</li>
<li><p>ip地址的分类</p>
<ul>
<li><p>ipv4 / ipv6</p>
<ul>
<li><p>IPV4 127.0.0.1 四个字节组成  42亿    2011年已被用尽</p>
</li>
<li><p>IPV6 128位、8个无符号整数组成  abcde</p>
<p><code>2834:4bba:aacb:0013:1241:1aaa:1341:6254</code></p>
</li>
</ul>
</li>
<li><p>公网 (互联网）- 私网（局域网）</p>
<ul>
<li>ABCD类地址</li>
</ul>
</li>
</ul>
</li>
<li><p>域名：记忆IP问题</p>
</li>
</ul>
<p>获取相关信息</p>
<pre><code class="java">public class TestInterAddress &#123;
    public static void main(String[] args) &#123;
        try &#123;
            InetAddress inetAddress1 = InetAddress.getByName(&quot;127.0.0.1&quot;);
            System.out.println(inetAddress1);

            InetAddress inetAddress2 = InetAddress.getByName(&quot;localhost&quot;);
            System.out.println(inetAddress2);

            InetAddress inetAddress3 = InetAddress.getLocalHost();
            System.out.println(inetAddress3);

            InetSocketAddress inetSocketAddress = new InetSocketAddress(&quot;127.0.0.1&quot;, 8080);
            System.out.println(inetSocketAddress);

            //查询网站IP地址
            InetAddress inetAddress4 = InetAddress.getByName(&quot;www.baidu.com&quot;);
            System.out.println(inetAddress4);

            System.out.println( inetAddress4.getCanonicalHostName());
            System.out.println( inetAddress4.getHostAddress());
            System.out.println( inetAddress4.getHostName());
            System.out.println( inetAddress4.getClass());


        &#125;catch (Exception e) &#123;
            e.printStackTrace();
        &#125;
    &#125;
&#125;
</code></pre>
<h2 id="端口"><a href="#端口" class="headerlink" title="端口"></a>端口</h2><p>端口表示计算机上的一个程序的进程：</p>
<ul>
<li><p>不同的进程有不同的端口号，用来区分软件。</p>
</li>
<li><p>被规定范围 0 - 65535</p>
</li>
<li><p>TCP，UDP ：65535*2   TCP 用80  UDP也可以用80  单个协议下，端口号不能冲突</p>
</li>
<li><p>端口分类</p>
<ul>
<li>公有端口 0-1023 系统进程使用，尽量不用<ul>
<li>HTTP : 80</li>
<li>HTTPS : 443</li>
<li>FTP : 21</li>
<li>Telent : 23</li>
</ul>
</li>
<li>程序注册端口，1024-49151，分配用户或者程序<ul>
<li>Tomcat : 8080</li>
<li>MySql : 3306</li>
<li>Oracle ：1521</li>
<li>postgre : 5432</li>
</ul>
</li>
<li>动态，私有：49152 - 65535</li>
</ul>
<pre><code class="java">netstat -ano 查看所有端口
    
netstat -ano|findstr &quot;5900&quot;   查看指定端口
    
tasklist|findstr &quot;8696&quot;  查看指定端口的进程
    
任务管理器  ctrl + shift + esc
</code></pre>
</li>
</ul>
<h2 id="通信协议"><a href="#通信协议" class="headerlink" title="通信协议"></a>通信协议</h2><p>协议：约定，就好比我们现在说的是普通话；</p>
<p>网络通信协议：速率，传输码率，代码结构，传输控制……</p>
<p>问题：非常的复杂？</p>
<p>大事化小：分层；</p>
<p>TCP/IP协议簇：<strong>实际上是一组协议</strong></p>
<p>重要：</p>
<ul>
<li><p>TCP:：用户传输协议；</p>
</li>
<li><p>UDP：用户数据报协议；</p>
</li>
<li><p>IP：网络互连协议；</p>
</li>
</ul>
<p>TCP / UDP对比</p>
<ul>
<li><strong>TCP</strong>： 连接稳定、<code>三次握手四次挥手</code>、客户端与服务端、传输需要释放效率低；</li>
<li><strong>UDP</strong>: 不连接不稳定、客户端服务端无明确界限、无需准备、 DDOS洪泛攻击；</li>
</ul>
<h2 id="TCP"><a href="#TCP" class="headerlink" title="TCP"></a>TCP</h2><p>客户端</p>
<ol>
<li>连接服务器 Socket；</li>
<li>发送消息；</li>
</ol>
<pre><code class="java">//客户端
public class TcpClientDemo1 &#123;
    public static void main(String[] args) &#123;
        Socket socket = null;
        OutputStream os = null;
        try &#123;
            //要知道服务器的地址
            InetAddress serverIP = InetAddress.getByName(&quot;127.0.0.1&quot;);
            int port = 9999;
            //创建一个socket连接
            socket = new Socket(serverIP, port);
            //发送消息
            os = socket.getOutputStream();
            os.write(&quot;message！&quot;.getBytes());
        &#125;catch (Exception e) &#123;
            e.printStackTrace();
        &#125; finally &#123;
            if (os!=null)&#123;
                try &#123;
                    os.close();
                &#125; catch (IOException e) &#123;
                    e.printStackTrace();
                &#125;
            &#125;
            if (socket!=null)&#123;
                try &#123;
                    socket.close();
                &#125; catch (IOException e) &#123;
                    e.printStackTrace();
                &#125;
            &#125;
        &#125;
    &#125;
&#125;
</code></pre>
<p>服务器</p>
<ol>
<li>建立服务的端口 ServerSocket；</li>
<li>等待用户的链接 accept；</li>
<li>接收用户的消息；</li>
</ol>
<pre><code class="java">//服务端
public class TcpServerDemo1 &#123;
    public static void main(String[] args) throws Exception &#123;

        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream bs = null;
        try &#123;
            //有一个服务器地址
             serverSocket = new ServerSocket(9999);
            //等待客户端连接
            socket = serverSocket.accept();
            //读取客户端的信息
            is = socket.getInputStream();
            //管道流
            bs = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) &#123;
                bs.write(buffer, 0, len);
            &#125;
            System.out.println(bs.toString());
        &#125; catch (Exception e) &#123;
            e.printStackTrace();
        &#125; finally &#123;
            if (bs != null) &#123;
                try &#123;
                    bs.close();
                &#125;catch (Exception e)&#123;
                    e.printStackTrace();
                &#125;
            &#125;
            if (is != null) &#123;
                try &#123;
                    is.close();
                &#125;catch (Exception e)&#123;
                    e.printStackTrace();
                &#125;
            &#125;
            if (socket != null) &#123;
                try &#123;
                    socket.close();
                &#125;catch (Exception e)&#123;
                    e.printStackTrace();
                &#125;
            &#125;
            if (serverSocket != null) &#123;
                try &#123;
                    serverSocket.close();
                &#125;catch (Exception e)&#123;
                    e.printStackTrace();
                &#125;
            &#125;
        &#125;
    &#125;
&#125;
</code></pre>
<h2 id="TCP文件上传"><a href="#TCP文件上传" class="headerlink" title="TCP文件上传"></a>TCP文件上传</h2><p>客户端</p>
<pre><code class="java">//客户端提交文件
public class TcpClientDemo2 &#123;
    public static void main(String[] args) &#123;
        Socket socket = null;
        OutputStream os = null;
        FileInputStream fis = null;
        try &#123;
            //创建一个socket连接
            socket = new Socket(InetAddress.getByName(&quot;127.0.0.1&quot;), 9000);
            //创建一个输出流
            os = socket.getOutputStream();
            //读取文件
            fis = new FileInputStream(new File(&quot;D:\\workspace\\IDEA-workspace\\kuangshen_java\\网络编程\\src\\com\\inte\\tcp\\bg17.jpg&quot;));
            //写出文件
            byte[] buffer = new byte[1024];
            int len;
            while ((len=fis.read(buffer))!=-1) &#123;
                os.write(buffer, 0, len);
            &#125;
        &#125; catch (Exception e) &#123;
            e.printStackTrace();
        &#125; finally &#123;
            //关闭资源
            if (fis!=null) &#123;
                try &#123;
                    fis.close();
                &#125;catch (Exception e) &#123;
                    e.printStackTrace();
                &#125;
            &#125;
            if (os!=null) &#123;
                try &#123;
                    os.close();
                &#125;catch (Exception e) &#123;
                    e.printStackTrace();
                &#125;
            &#125;
            if (socket!=null) &#123;
                try &#123;
                    socket.close();
                &#125;catch (Exception e) &#123;
                    e.printStackTrace();
                &#125;
            &#125;
        &#125;
    &#125;
&#125;
</code></pre>
<p>服务端</p>
<pre><code class="java">//服务端接收文件
public class TcpServerDemo2 &#123;
    public static void main(String[] args) &#123;
        //创建服务
        ServerSocket serverSocket = null;
        //监听客户端的连接
        Socket socket = null;
        //获取输入流
        InputStream is = null;
        //文件输出
        FileOutputStream fos = null;

        try &#123;
            serverSocket = new ServerSocket(9000);
            socket = serverSocket.accept(); //阻塞式监听，会一直等待客户端连接
            is = socket.getInputStream();
            fos = new FileOutputStream(new File(&quot;D:\\workspace\\IDEA-workspace\\kuangshen_java\\网络编程\\src\\com\\inte\\tcp\\&quot; + Math.random()*1000000000 + &quot;.jpg&quot;));
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len=is.read(buffer))!=-1)&#123;
                fos.write(buffer, 0, len);
                System.out.println(&quot;接收文件.....&quot;);
            &#125;
        &#125; catch (Exception e) &#123;
            e.printStackTrace();
        &#125; finally &#123;
            //关闭资源
            if (fos!=null) &#123;
                try &#123;
                    fos.close();
                &#125;catch (Exception e) &#123;
                    e.printStackTrace();
                &#125;
            &#125;
            if (is!=null) &#123;
                try &#123;
                    is.close();
                &#125;catch (Exception e) &#123;
                    e.printStackTrace();
                &#125;
            &#125;
            if (socket!=null) &#123;
                try &#123;
                    socket.close();
                &#125;catch (Exception e) &#123;
                    e.printStackTrace();
                &#125;
            &#125;
            if (serverSocket!=null) &#123;
                try &#123;
                    serverSocket.close();
                &#125;catch (Exception e) &#123;
                    e.printStackTrace();
                &#125;
            &#125;
        &#125;
    &#125;
&#125;
</code></pre>
<h2 id="Tomcat"><a href="#Tomcat" class="headerlink" title="Tomcat"></a>Tomcat</h2><p>服务端</p>
<ul>
<li>自定义 S</li>
<li>Tomcat服务器 S : JAVA后台开发</li>
</ul>
<p>客户端</p>
<ul>
<li>自定义 C</li>
<li>浏览器 B</li>
</ul>
<h2 id="UDP"><a href="#UDP" class="headerlink" title="UDP"></a>UDP</h2><p>Client1</p>
<pre><code class="java">public static void main(String[] args) throws Exception &#123;
        //建立一个socket
        DatagramSocket socket = new DatagramSocket();

        //建个包
        String msg = &quot;hello my friend!!&quot;;

        //发送给谁
        InetAddress localhost = InetAddress.getByName(&quot;localhost&quot;);
        int port = 9090;

        //数据，数据的长度起始，要发送给谁；
        DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);

        //发送包
        socket.send(datagramPacket);

    &#125;
</code></pre>
<p>Client2</p>
<pre><code class="java">public static void main(String[] args) throws Exception &#123;
        //开放端口
        DatagramSocket socket = new DatagramSocket(9090);

        //接收数据包
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);

        socket.receive(packet);  //阻塞接受

        System.out.println(new String(packet.getData(), 0, packet.getLength() ));

        socket.close();
    &#125;
</code></pre>
<h2 id="案例：UDP实现聊天"><a href="#案例：UDP实现聊天" class="headerlink" title="案例：UDP实现聊天"></a>案例：UDP实现聊天</h2><pre><code class="java">//发送方
public static void main(String[] args) throws Exception &#123;
        DatagramSocket socket = new DatagramSocket(8888);
        // 准备数据 从控制台读取 system.in
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        while (true)&#123;
            String data = reader.readLine();
            byte[] datas = data.getBytes();
            DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(&quot;localhost&quot;, 6666));

            socket.send(packet);
            if(data.equals(&quot;bye&quot;)) &#123;
                break;
            &#125;
        &#125;
        socket.close();
    &#125;
</code></pre>
<pre><code class="java">//接收方
 public static void main(String[] args) throws Exception &#123;
        DatagramSocket socket = new DatagramSocket(6666);

        while(true)&#123;
            // prepare receive the packet
            byte[] container = new byte[1024];
            DatagramPacket packet = new DatagramPacket(container, 0, container.length);
            socket.receive(packet); // 阻塞式接收

            // 断开连接 bye
            byte[] data = packet.getData();
            String receiveData = new String(data, 0, data.length);
            System.out.print(receiveData);
            if (receiveData.equals(&quot;bye&quot;)) break;
        &#125;
        socket.close();
    &#125;
</code></pre>
<p>多线程：实现同时收发</p>
<pre><code class="java">import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class TalkReceive implements Runnable &#123;
    DatagramSocket socket = null;
    private int port;
    private String msgFrom;
    public TalkReceive(int port, String msgFrom)&#123;
        this.port = port;
        this.msgFrom = msgFrom;
        try &#123;
            socket = new DatagramSocket(port);
        &#125; catch (SocketException e) &#123;
            e.printStackTrace();
        &#125;
    &#125;
    @Override
    public void run() &#123;
        try &#123;
            while(true)&#123;
                // prepare receive the packet
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container, 0, container.length);
                socket.receive(packet); // 阻塞式接收

                // 断开连接 bye
                byte[] data = packet.getData();
                String receiveData = new String(data, 0, data.length);
                System.out.println(msgFrom + &quot;:&quot; + receiveData);
                if (receiveData.equals(&quot;bye&quot;)) break;
            &#125;
        &#125; catch (IOException e) &#123;
            e.printStackTrace();
        &#125;
        socket.close();
    &#125;
&#125;
</code></pre>
<pre><code class="java">import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class TalkSend implements Runnable &#123;
    DatagramSocket socket = null;
    BufferedReader reader = null;
    private int fromPort;
    private String toIP;
    private int toPort;

    public TalkSend(int fromPort, String toIP, int toPort) &#123;
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;
        try&#123;
            socket = new DatagramSocket(fromPort);
            reader = new BufferedReader(new InputStreamReader(System.in));
        &#125;catch (Exception e)&#123;
            e.printStackTrace();
        &#125;
    &#125;

    @Override
    public void run() &#123;
        while (true)&#123;
            String data = null;
            try &#123;
                data = reader.readLine();
                byte[] datas = data.getBytes();
                DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(this.toIP, this.toPort));

                socket.send(packet);
                if(data.equals(&quot;bye&quot;)) &#123;
                    break;
                &#125;
            &#125; catch (IOException e) &#123;
                e.printStackTrace();
            &#125;
        &#125;
        socket.close();
    &#125;
&#125;
</code></pre>
<pre><code class="java">public class TalkStu &#123;
    public static void main(String[] args) &#123;
        // 开启两个线程
        new Thread(new TalkSend(7878, &quot;localhost&quot;, 9988)).start();
        new Thread(new TalkReceive(8899, &quot;teac&quot;)).start();
    &#125;
&#125;
</code></pre>
<pre><code class="java">public class TalkTeac &#123;
    public static void main(String[] args) &#123;
        new Thread(new TalkSend(5555, &quot;localhost&quot;, 8899)).start();
        new Thread(new TalkReceive(9988, &quot;Stu&quot;)).start();
    &#125;
&#125;
</code></pre>
<h2 id="URL"><a href="#URL" class="headerlink" title="URL"></a>URL</h2><p>统一资源定位符：定位资源，定位互联网上的某一个资源</p>
<p>DNS域名解析  :     协议：// ip 地址：端口/ 项目名 / 资源</p>
<p>下载网络资源:</p>
<pre><code class="java">public class UrlDownload &#123;
    public static void main(String[] args) throws Exception &#123;
        // 1. download Address
        URL url = new URL(&quot;url&quot;); // 网络资源地址
        // 2. connect HTTP
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        InputStream inputStream = urlConnection.getInputStream();

        FileOutputStream fos = new FileOutputStream(&quot;fileName.txt&quot;); // 下来的命名

        byte[] buffer = new byte[1024];
        int len;
        while((len = inputStream.read(buffer)) != -1)&#123;
            fos.write(buffer, 0, len); // 写出数据
        &#125;
        fos.close();
        inputStream.close();
        urlConnection.disconnect(); // 断开连接
    &#125;
&#125;
</code></pre>

  </article>

  
    
  <div class="nexmoe-post-copyright">
    <strong>本文作者：</strong>shanX<br>
    <strong>本文链接：</strong><a href="https://rhymexmove.github.io/2021/04/12/6b4cf36b2046/" title="https:&#x2F;&#x2F;rhymexmove.github.io&#x2F;2021&#x2F;04&#x2F;12&#x2F;6b4cf36b2046&#x2F;" target="_blank" rel="noopener">https:&#x2F;&#x2F;rhymexmove.github.io&#x2F;2021&#x2F;04&#x2F;12&#x2F;6b4cf36b2046&#x2F;</a><br>
    
      <strong>版权声明：</strong>本文采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/cn/deed.zh" target="_blank">CC BY-NC-SA 3.0 CN</a> 协议进行许可
    
  </div>


  
  
  <div class="nexmoe-post-meta nexmoe-rainbow">
    
        <a class="nexmoefont icon-appstore-fill -link" href="/categories/java/">java</a>
    
    
        <a class="nexmoefont icon-tag-fill -none-link" href="/tags/java%E5%9F%BA%E7%A1%80/" rel="tag">java基础</a> <a class="nexmoefont icon-tag-fill -none-link" href="/tags/%E7%8B%82%E7%A5%9E%E8%AF%B4/" rel="tag">狂神说</a>
    
</div>

  <div class="nexmoe-post-footer">
    <section class="nexmoe-comment">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1.7.2/dist/gitalk.min.css">
<div id="gitalk"></div>
<script src="https://cdn.jsdelivr.net/npm/gitalk@1.7.2/dist/gitalk.min.js"></script>
<script type="text/javascript">
    var gitalk = new Gitalk({
        clientID: 'a2d666d91d6af126f538',
        clientSecret: '9c79e44494cd9fae312629457ae9b534e01a963e',
        id: decodeURI(window.location.pathname),
        repo: 'RhymeXmove.github.io',
        owner: 'RhymeXmove',
        admin: 'RhymeXmove'
    })
    gitalk.render('gitalk')
</script>
</section>
  </div>
</div>
                            <div class="nexmoe-post-right">
                                <div class="nexmoe-fixed">
                                    <div class="nexmoe-tool">
                                        <a href="#nexmoe-content" class="toc-link" aria-label="回到顶部" title="top"><button class="mdui-fab mdui-ripple"><i class="nexmoefont icon-caret-top"></i></button></a>
                                    </div>
                                </div>
                            </div>
                    </div>
                </div>
                <script src="https://cdn.jsdelivr.net/combine/npm/lazysizes@5.1.0/lazysizes.min.js,gh/highlightjs/cdn-release@9.15.8/build/highlight.min.js,npm/mdui@0.4.3/dist/js/mdui.min.js?v=1"></script>
<script>
	hljs.initHighlightingOnLoad();
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js"></script>


<script src="https://cdn.jsdelivr.net/gh/xtaodada/xtaodada.github.io@0.0.2/copy.js"></script>
 

<script src="/js/app.js?v=1649858550949"></script>

<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.8.1/dist/js/jquery.justifiedGallery.min.js"></script>
<script>
	$(".justified-gallery").justifiedGallery({
		rowHeight: 160,
		margins: 10,
	});
</script>

                    





        </body>

</html>